import Vue from 'vue'
import Vuex from 'vuex'
// import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: [],
    inputVal: 'aaa',
    viewType: 'all'
  },
  mutations: {
    setList(state, list) {
      state.list = list
    },
    setInputVal(state, value) {
      state.inputVal = value
    },
    setViewType(state, value) {
      console.log(value)
      state.viewType = value
    },
    addItem(state) {
      const id =
        Math.max.apply(
          this,
          state.list.map(item => item.id)
        ) + 1
      console.log(id)
      const obj = {
        id: id,
        info: state.inputVal,
        done: false
      }
      state.list.push(obj)
      state.inputVal = ''
      this.commit('saveToLocal')
    },
    removeItem(state, id) {
      const i = state.list.findIndex(item => item.id === id)
      state.list.splice(i, 1)
      this.commit('saveToLocal')
    },
    removeCheckedItem(state) {
      state.list = state.list.filter(item => !item.done)
      this.commit('saveToLocal')
    },
    updateItem(state, obj) {
      console.log(obj.id, obj.done)
      const item = state.list.find(item => item.id === obj.id)
      item.done = obj.done
      this.commit('saveToLocal')
    },
    saveToLocal(state) {
      localStorage.setItem('todoList', JSON.stringify(state.list))
    }
  },
  actions: {
    async getList(ctx) {
      // const { data } = await axios.get('/list.json')
      const data = JSON.parse(localStorage.getItem('todoList')) ?? []
      // console.log(data)
      ctx.commit('setList', data)
    }
  },
  getters: {
    unDoneLenth(state) {
      return state.list.filter(item => !item.done).length
    },
    viewList(state) {
      switch (state.viewType) {
        case 'all':
          return state.list
        case 'undone':
          return state.list.filter(item => !item.done)
        case 'done':
          return state.list.filter(item => item.done)
      }
    }
  },
  modules: {}
})
